﻿using System;
using System.Collections.Generic;

namespace POP.Mime.Traverse
{
	public abstract class AnswerMessageTraverser<TAnswer> : IAnswerMessageTraverser<TAnswer>
	{
		// Call this when you want an answer for a full message.
		public TAnswer VisitMessage(Message message)
		{
			if(message == null)
				throw new ArgumentNullException("message");

			return VisitMessagePart(message.MessagePart);
		}

		public TAnswer VisitMessagePart(MessagePart messagePart)
		{
			if(messagePart == null)
				throw new ArgumentNullException("messagePart");

			if(messagePart.IsMultiPart)
			{
				List<TAnswer> leafAnswers = new List<TAnswer>(messagePart.MessageParts.Count);
				foreach (MessagePart part in messagePart.MessageParts)
				{
					leafAnswers.Add(VisitMessagePart(part));
				}
				return MergeLeafAnswers(leafAnswers);
			}

			return CaseLeaf(messagePart);
		}

		// <summary>
		protected abstract TAnswer CaseLeaf(MessagePart messagePart);

		protected abstract TAnswer MergeLeafAnswers(List<TAnswer> leafAnswers);
	}
}